//
//  HomeViewController.swift
//  sinaWeibo
//
//  Created by hjun on 16/3/20.
//  Copyright © 2016年 hjun. All rights reserved.
//

import UIKit

import SVPullToRefresh
class HomeViewController: HJBaseViewController {
    ///cell标识
    private let ReuseIdentifier = "ReuseIdentifier"
    
    ///微博数据
    var statuses: [HJStatus]?{
        
        didSet{
            tableView.reloadData()
        }
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        ///登录以后才做后面的操作
        if !HJUserAccountViewModel.sharedInstance.userLogin{
            return
        }
        //设置导航栏
        setupUINavgationBar()
        
        //设置title
        setTitle()
        
        ///tableview
        prepareTableview()
    }
    ///下拉刷新
    private func loadNewStatus(){
        
        
        ///获取id'最大的微博
        let since_id = self.statuses?.first?.id ?? 0
        
        
        ///使用HJStatusViewModel加载微博首页数据
        HJStatusViewModel.sharedInstance.loadStatus(since_id, max_id: 0 ){(status, error) -> () in
            
            ///进去之前结束刷新 不然风火轮一直转动
            self.tableView.endRefreshing()
            
            if error != nil{
                
                print("下拉刷新加载微博数据出错")
                return
            }
            
            let count = status?.count ?? 0
            
            if since_id > 0 {
                
                self.loadpullDownStatusTipLabel(count)
                
            }
            
            if count == 0{
                
                HJPrint(msg: "下拉刷新没有加载到微博数据")
                return
            }
            
            if since_id > 0{
                
                ///将获取的最新微博放在前面
                self.statuses = status! + self.statuses!
                
                
            }else{
                ///加载20条微博数据
                self.statuses = status
                
            }
        }
    }
    
    ///上拉加载微博数据
    private func loadMoreStatus(){
        
        ///获取最后的微博数
        let max_id = statuses?.last?.id ?? 0
        
        HJStatusViewModel.sharedInstance.loadStatus(0, max_id: max_id) { (status, error) -> () in
            ///结束上拉加载更多数据
            
            self.tableView.infiniteScrollingView.stopAnimating()
            
            if error != nil{
                
                HJPrint(msg: "上拉加载微博数据出错")
                return
            }
            
            let count = status?.count ?? 0
            
            if count == 0{
                
                HJPrint(msg: "上拉没有加载到微博数据")
                return
            }
            
            
            self.statuses = status! + self.statuses!
            
        }
        
    }
    
    private func prepareTableview(){
        
        ///注册cell
        tableView.registerClass(HJStatusesCell.self, forCellReuseIdentifier: ReuseIdentifier)
        ///cell的高度
        
        //tableView.rowHeight = 100
        tableView.estimatedRowHeight = 80
        tableView.rowHeight = UITableViewAutomaticDimension
        ///取消cell的间隔线
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
        ///将pullDownRefreshControl添加到tableView
        ///tableView.addSubview(pullDownRefreshControl)
        
        ///封装完成的下拉刷新控件
        
        tableView.addPullDownRefreshHandle ({ [weak self]() -> () in
            
            self?.loadNewStatus()
            
            })
        
        tableView.startRefrshing()
        
        ///上拉加载微博数据
        
        tableView.addInfiniteScrollingWithActionHandler { [weak self]() -> Void in
            
            self?.loadMoreStatus()
        }
        
    }
    ///下拉刷新条数
    func loadpullDownStatusTipLabel(count: Int){
        
        tipLabel.text = count == 0 ? "没有新的微博数据" : "更新了\(count)条微博"
        
        UIView.animateWithDuration(HJDefaultDuration * 4) { () -> Void in
            
            self.tipLabel.frame.origin.y = 44
            
            UIView.animateWithDuration(HJDefaultDuration * 4, delay: 2, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
                
                self.tipLabel.frame.origin.y = -64
                }, completion: nil)
        }
        
        
    }
    
    
    
    private func setTitle(){
        
        let name = HJUserAccountViewModel.sharedInstance.userAccount?.screen_name
        
        let titleButton = HJHomeTitleButton(title: name, imageName: "navigationbar_arrow_down")
        titleButton.addTarget(self, action: "didClickTitleButtonAction:", forControlEvents: UIControlEvents.TouchUpInside)
        navigationItem.titleView = titleButton
        
    }
    
    ///titleButton的点击事件
    
    func didClickTitleButtonAction(button:HJHomeTitleButton){
        
        button.selected = !button.selected
        
        UIView.animateWithDuration(HJDefaultDuration) { () -> Void in
            
            button.imageView?.transform = button.selected ? CGAffineTransformMakeRotation(CGFloat(M_PI-0.001)) : CGAffineTransformIdentity
        }
        
        if button.selected{
            
            let btnVc = HJPopverViewController()
            ///设置btnVC的显示样式
            btnVc.modalPresentationStyle = .Popover
            
            ///设置UIPopoverPresentationControllerDelegate来让不要适配iphone
            btnVc.popoverPresentationController?.delegate = self
            ///箭头指向位置titileView
            btnVc.popoverPresentationController?.sourceView = navigationItem.titleView
            
            ///设置箭头指向具体位置
            btnVc.popoverPresentationController?.sourceRect = (navigationItem.titleView?.bounds)!
            ///设置popver的size大小
            btnVc.preferredContentSize = CGSize(width: 200, height: 44 * btnVc.titles.count)
            
            
            presentViewController(btnVc, animated: true, completion: nil)
            
        }
    }
    
    
    ///设置barbuttonitem
    
    private func setupUINavgationBar(){
        
        ///便利构造函数方法调用
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch", target: self, action: "didClickLeftBarButtonItem")
        
        ///便利构造函数方法
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: "didClickRightBarButtonItem")
    }
    
    
    func didClickLeftBarButtonItem(){
        
    }
    
    func didClickRightBarButtonItem(){
        
    }
    //MARK: 懒加载
    
    private lazy var pullDownRefreshControl: PullDownRefreshControl = PullDownRefreshControl()
    
    ///下拉刷新提示label
    private lazy var tipLabel: UILabel = {
        
        let label = UILabel()
        label.backgroundColor = UIColor.orangeColor()
        label.tintColor = UIColor.whiteColor()
        label.font = UIFont.systemFontOfSize(18)
        label.textAlignment = NSTextAlignment.Center
        label.frame = CGRect(x: 0, y: -64, width: UIScreen.width, height: 44)
        
        ///不能添加到tableview上 不然会跟着跑 要添加到navgation上
        self.navigationController?.navigationBar.insertSubview(label, atIndex: 0)
        
        return label
    }()
    
    
}


///定义tableview
extension HomeViewController{
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return statuses?.count ?? 0
        
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier(ReuseIdentifier, forIndexPath: indexPath) as! HJStatusesCell
        
        
        cell.status = statuses?[indexPath.row]
        
        
        return cell
    }
    ///取消cell的选中
    override func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        return false
    }
    
}

///在HomeViewController 中实现 UIPopoverPresentationControllerDelegate代理方法
extension HomeViewController: UIPopoverPresentationControllerDelegate{
    //默认适配是全屏 设置下面代理方法取消
    func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
        
        return  UIModalPresentationStyle.None
        
    }
    
    ///箭头转动的方向
    func popoverPresentationControllerShouldDismissPopover(popoverPresentationController: UIPopoverPresentationController) -> Bool {
        
        let titleBtn = navigationItem.titleView as! HJHomeTitleButton
        
        didClickTitleButtonAction(titleBtn)
        
        return true
    }
    
}
